<template>
  <div class="relative">
    <div class="environment-header">
      <p class="title left">塔吊监控</p>
      <div class="head-right">
        <span class="mr10 ml20">视图</span>
        <zz-select
          class="inline mr10"
          style="width: 152px"
          :border= true
          :options="{width: '100%'}"
          :option="themeList"
          :all = false
          optionColor = "#939997"
          :name = shituName
          @optionClick="changeView">
        </zz-select>
        <span class="mr10" v-if="searchByPro">区域</span>
        <zz-select v-if="searchByPro"
          class="inline mr10"
          style="width: 152px"
          :border= true
          :options="{width: '100%'}"
          :option="areaList"
          :all = false
          optionColor = "#939997"
          name = "全部区域"
          @optionClick="changeArea">
        </zz-select>
        <span class="mr10" v-if="searchByPro">项目</span>
        <zz-search v-if="searchByPro"
          class="inline mr10"
          :width="155"
          :searchTop="4"
          @searchClick="searchClickByPro">
        </zz-search>
        <span class="mr10" v-if="!searchByPro">区域</span>
        <zz-search v-if="!searchByPro"
          class="inline mr10"
          :width="155"
          :searchTop="4"
          @searchClick="searchClickByCo">
        </zz-search>
      </div>
    </div>
    <div class="top-right right">
      <button class="button-block mr20 " @click="isShowDialog('1')" v-if="searchByPro">无塔吊设备的项目({{rate.noDeviceProjectNum}})</button>
      <button class="button-block mr20 " @click="isShowDialog('2')">今日塔吊报警系统({{rate.alarmcount}})</button>
      <span class="mr10">排序</span>
      <zz-select
        class="inline mr10"
        style="width: 152px"
        :border= true
        :options="{width: '100%'}"
        :option="sortList1"
        :all = false
        optionColor = "#939997"
        name = "监控比例"
        @optionClick="sortBy">
      </zz-select>
      <zz-select
        class="inline"
        style="width: 99px"
        :border= true
        :options="{width: '100%'}"
        :option="sortList2"
        :all = false
        optionColor = "#939997"
        name = "降序"
        @optionClick="changeSortFun">
      </zz-select>
    </div>
    <div class="info mr20">
      <div>塔吊数量<span>{{rate.deviceNum}}</span>台</div>
      <div>监控数量<span>{{rate.monitorNum}}</span>台</div>
      <div>监控比例<span>{{rate.monitorPercent}}%</span></div>
      <div>监控在线率<span>{{rate.onlinePercent}}%</span></div>
    </div>
    <zz-table
      style="width: 100%;"
      :title="title"
      :dataList = 'dataList'
      @handle="tableHandler">
    </zz-table>
    <zz-paginate pagingId="page3" :simple="false" :isTotalItem="false" :pageSize = pageSize  v-if="dataList.length > 0" @choose="query" :padding="[0]" class="right mr20"></zz-paginate>
    <div class="exportExcel ml20">
      <button class="mr10 button-block" @click="exportExcel()">导出Excel</button>
      <div>上述每小时统计一次，本次数据更新时间：<span v-if="updateTime">{{$moment(updateTime).format('HH:mm:ss')}}</span></div>
    </div>

    <zz-dialog
      :title = dialogTitle
      :visible = showDialog
      :showConfirm = false
      :reset = true
      :showFoot = "false"
      @close="close">
      <div class="dialog-box">
        <!-- 没有数据 -->
        <div v-if="todayDialogShow && showNoNum" style="width: 300px; height: 30px;text-align: center;">
          暂无数据
        </div>
        <!-- 今日报警弹窗 -->
        <div v-if = "todayDialogShow && !showNoNum" style="width: 400px; height: 350px">
          <div ref="towerMonitorEchart" style="width: 100%; height: 100%"></div>
        </div>
        <!-- 无塔吊设备项目的弹窗 -->
        <div v-if = "noTowerDialogShow" style="width: 800px; height: 520px; overflow: hidden;">
          <zz-table
            style="margin: 0 -20px 0"
            :title="dialogTableTitle"
            :dataList = 'detailDataList'>
          </zz-table>
          <zz-paginate pagingId="page4" pageSize = 10 :simple="false" :isTotalItem="false" v-if="detailDataList.length > 0" @choose="detailQuery" :padding="[0]" class="right"></zz-paginate>
          <div class="exportExcel">
            <button class="mr10 button-block" @click="exportNoMonitorExcel()">导出Excel</button>
            <!-- <div>上述每小时统计一次，本次数据更新时间：<span>12:30:30</span></div> -->
          </div>
        </div>
      </div>
    </zz-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import { mapGetters } from 'vuex'
import pie from '../../../js/pie2.js'
import { getDeviceMonitor, getComTowerByArea, getComTowerByProject, getComTodayTowerAlarm, noMonitorList, getTowerDepartmentList, getComTowerByProjectExport } from '../../../service/api.js'

export default {
    name: 'videomonitor',
    components: {
    },
    computed: {
      ...mapGetters({
        currentUser: 'currentUser'
      })
    },
    data () {
      return {
        rate: {
          towerNum: 0,
          monitorNum: 0,
          monitorPercent: '0',
          onlinePercent: '0',
          noDeviceProjectNum: 0,
          alarmcount: 0
        },
        shituName: '',
        areaId: '', // 区域id
        searchKeyword: '',
        searchAreaWord: '',
        themeList: {
          1: '按区域/城市公司',
          2: '按项目'
        },
        sortList1: {},
        sortList2: {
          1: '降序',
          0: '升序'
        },
        areaList: {
           1: '全部区域',
        },
        dataList: [],
        detailDataList: [],
        showArea: false,
        title: [],
        carouselArea: '',
        searchByPro: false,
        showDialog: false,
        dialogTitle: '',
        dataAccessRangeCode: '',
        dialogTableTitle: [
          {name: '序号', width: '11%', align: 'left'},
          {name: '项目名称', width: '20%', align: 'left'},
          {name: '区域', width: '15%', align: 'left'},
          {name: '项目负责人', width: '22%', align: 'left'},
          {name: '上线智慧工地时间', width: '22%', align: 'left'}
        ],
        page: 1,
        pageSize: 10,
        noAccessPage: 1,
        noTowerDialogShow: false,
        todayDialogShow: false,
        totalWarn: null,
        totalWarnOption: null,
        totalWarnOptions: {
          data: [],
          color: ['#33cadb', '#60bbf2', '#48dba4', '#afe551', '#a3c3fe', '#cbf1f4', '#d4c054', '#d49054', '#54a8d4', '#546fd4', '#7e54d4', '#b154d4', '#5472d4'],
        },
        totalWarnNum: null,
        groupObject: 0,   //0监控比率，1在线率，2有效工作时长， 3今日报警
        order: 1, //0升序   1降序
        isExport: 0, // 1 导出
        path: '' ,
        defaultNum: '',
        updateTime: '',
        noAccessUpTime: '',
        showNoNum: false
      }
    },
    mounted () {
      this.getOnlineList()
      this.findUserDataAccessRange().then(() => {
        this.setDataOption()
      })
    },
    methods: {
      findUserDataAccessRange () {
        return new Promise(resolve => {
          let data = {
            'dataAccessRange.fun_code': 'c_tcMonitor_browse',
            'dataAccessRange.company_id': this.currentUser.coId
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.companyServer}/front/findUserDataAccessRange.htm`,
            data: this.$qs.stringify(data, {indices: false})
          }).then(res => {
            this.dataAccessRangeCode = res.data.dataAccessRange.code
            resolve()
          })
        })
      },
      setDataOption () {
        if (this.dataAccessRangeCode === 5 || this.dataAccessRangeCode === 4) {
          this.shituName = '按区域/城市公司'
          this.themeList = {
            1: '按区域/城市公司',
            2: '按项目'
          }
          this.changeView({key: "1"})
        } else {
          this.shituName = '按项目'
          this.themeList = {
            2: '按项目'
          }
          this.changeView({key: "2"})
        }
      },
      // 弹窗显示
      isShowDialog (type) {
        this.showDialog = true
        switch(type) {
          case '1':
          this.noTowerDialogShow = true
          this.dialogTitle = '无塔吊设备的项目'
          this.getNoTowerDetailList()
          break
          case '2':
          this.todayDialogShow = true
          this.dialogTitle = '今日塔吊报警——全集团'
          this.getTodayTower()
          break
        }
      },
      // 跳转页面
      gopage (url, idnum, pname) {
        this.$router.push({ path: url, query: { id: idnum, name: pname }})
      },
      // 企业级/项目级
      changeView (item) {
        this.searchKeyword = ''
        this.searchAreaWord = ''
        this.updateTime = ''
        this.searchByPro = (item.key === "1" ? false : true)  // 1按区域 2按项目
        if (item.key === "1") {
          this.title = [
            {name: '区域名称', width: '11%', align: 'left'},
            {name: '智慧工地数量', width: '14%', align: 'left'},
            {name: '塔吊数量', width: '8%', align: 'left'},
            {name: '监控数量', width: '8%', align: 'left'},
            {name: '监控比例', width: '8%', align: 'left'},
            {name: '在线数量', width: '8%', align: 'left'},
            {name: '在线率', width: '8%', align: 'left'},
            {name: '平均有效工作时长(小时/日)', width: '20%', align: 'left'},
            {name: '操作', width: '15%', align: 'left'}
          ]
          this.sortList1 = {
            0: '监控比例',
            1: '在线率',
            2: '有效工作时间'
          }
        } else {
          this.title = [
            {name: '区域名称', width: '10%', align: 'left'},
            {name: '项目名称', width: '13%', align: 'left'},
            {name: '塔吊数量', width: '8%', align: 'left'},
            {name: '监控数量', width: '8%', align: 'left'},
            {name: '监控比例', width: '8%', align: 'left'},
            {name: '在线数量', width: '8%', align: 'left'},
            {name: '在线率', width: '8%', align: 'left'},
            {name: '今日报警', width: '8%', align: 'left'},
            {name: '平均有效工作时长(小时/日)', width: '20%', align: 'left'},
            {name: '操作', width: '10%', align: 'left'}
          ]
          this.sortList1 = {
          0: '监控比例',
          1: '在线率',
          2: '有效工作时间',
          3: '日均报警次数'
        },
          this.getDepartment()
        }
        this.getTowerList(item.key)
        this.getOnlineList()
      },
      // 查看塔吊在线率统计
      getOnlineList () {
        getDeviceMonitor({
          coId: this.currentUser.coId,
          areaCode: this.areaId, //区域id
          mid: this.currentUser.mid
        }).then( res => {
          this.rate = {
          deviceNum: res.data.deviceNum,
          monitorNum: res.data.monitorNum,
          monitorPercent: res.data.monitorPercent,
          onlinePercent: res.data.onlinePercent,
          noDeviceProjectNum: res.data.noDeviceProjectNum,
          alarmcount: res.data.alarmcount
        }
        }).catch( err => {
          console.log(err)
        })
      },
      changeArea (item) {
        if (item.key === '1') {
          item.key = ''
          this.areaId = item.key
        } else {
          this.areaId = item.key
        }
        this.searchByProject()
        this.getOnlineList()
        // 修改区域
      },
      sortBy (item) {
         // 修改排序方式
         this.groupObject = Number(item.key)
        if (this.searchByPro) {
          this.searchByProject()
        } else {
          this.searchByCompany()
        }
        this.getOnlineList()
      },
      changeSortFun (item) {
        this.order = Number(item.key)
        // 升降序修改
        if (this.searchByPro) {
          this.searchByProject()
        } else {
          this.searchByCompany()
        }
        this.getOnlineList()
      },
      searchClickByCo (item) {
        this.searchAreaWord = item
        this.searchByCompany()
        this.getOnlineList()
      },
      searchClickByPro (item) {
        this.searchKeyword = item
        this.searchByProject()
        this.getOnlineList()
      },
      query (item) {
        // 获取对应页数据
        if (this.searchByPro) {
          this.searchByProject()
        } else {
          this.searchByCompany()
        }
      },
      detailQuery (item) {
        // 无塔吊项目弹层的获取对应页数据
        this.noAccessPage = item
        this.getNoTowerDetailList()
      },
      // 获取企业级的塔吊监测数据
      getTowerList (type) {
        if (type === '1') {
          // 按区域城市查询
          this.searchByCompany()
        } else {
          // 按项目查询
          this.searchByProject()
        }
      },
      // 查看详情
      tableHandler (data) {
        if (this.searchByPro) {
          this.gopage('/tcMonitor/projectTower', data.data.projectId, data.data.projectName)
        } else {
          this.gopage('/tcMonitor/areaTower', data.data.areaCode, data.data.areaName)
        }
      },
      searchByCompany () {
        this.dataList = []
        let data = {
          'coId': this.currentUser.coId,
          'mid': this.currentUser.mid,
          'keywords': this.searchAreaWord, // 关键字
          'groupObject': this.groupObject,   // 0监控比率，1在线率，2有效工作时长， 3今日报警
          'order': this.order,    // 0升序   1降序
          // 'page': this.page,
          'pageSize': this.pageSize,
          'isExport': this.isExport, // 1 导出
          'path': this.path,  // 下载路径
          'mid': this.currentUser.mid
        }
        this.$axios({
            method: 'post',
            url: `${Vue.prototype.$site.videoServer}/api/towercrane/getComTowerByArea`,
            data: this.$qs.stringify(data, {indices: false}),
            paginate: true,
            paginId: 'page3'
          }).then(res => {
              this.dataList = res.data.data.dataList
              if (res.data.data.dataList && res.data.data.dataList.length > 0) {
                this.updateTime = res.data.data.dataList[0].updateTime
              }
              this.dataList = this.dataList.map(item => {
                return {
                  areaName: item.areaName,
                  projectNum: {customize: `<div style='text-align:right'>${item.projectNum && item.projectNum != 0 ? item.projectNum : '--' }</div>`},
                  towerNum: {customize: `<div style='text-align:right'>${item.towerNum && item.towerNum != 0 ? item.towerNum : '--'}</div>`},
                  monitorNum: {customize: `<div style='text-align:right'>${item.monitorNum && item.monitorNum != 0 ? item.monitorNum : '--'}</div>`},
                  monitorPercent: {customize: `<div style='text-align:right'>${item.monitorPercent && item.monitorPercent != 0 ? item.monitorPercent : '--'}</div>`},
                  onlineNum: {customize: `<div style='text-align:right'>${item.onlineNum && item.onlineNum != 0 ? item.onlineNum : '--'}</div>`},
                  onlinePercent: {customize: `<div style='text-align:right'>${item.onlinePercent && item.onlinePercent != 0 ? item.onlinePercent : '--'}</div>`},
                  avgWorktime: {customize: `<div style='text-align:right'>${item.avgWorktime && item.avgWorktime != 0 ? item.avgWorktime : '--'}</div>`},
                  handle: [{name: '查看详情', type: 'detail', data: item}]
                }
              })
          })
      // 按区域城市查询
      },
      searchByProject () {
        this.dataList = []
        let data = {
          'coId': this.currentUser.coId,
          'areaCode': this.areaId, //区域code
          'mid': this.currentUser.mid,
          'keywords': this.searchKeyword,
          'groupObject': this.groupObject,
          'order': this.order,
          // 'page': this.page,
          'pageSize': this.pageSize,
          'isExport': this.isExport, // 1 导出
          'path': this.path  // 下载路径
        }
        this.$axios({
            method: 'post',
            url: `${Vue.prototype.$site.videoServer}/api/towercrane/getComTowerByProject`,
            data: this.$qs.stringify(data, {indices: false}),
            paginate: true,
            paginId: 'page3',
          }).then(res => {
            if (res.data.data.dataList && res.data.data.dataList.length > 0) {
                 this.updateTime = res.data.data.dataList[0].updateTime
              }
            this.dataList = res.data.data.dataList
            this.dataList = this.dataList.map(item => {
              return {
                areaName: item.areaName,
                projectName: item.projectName,
                towerNum: {customize: `<div style='text-align:right'>${item.towerNum && item.towerNum != 0 ? item.towerNum : '--'}</div>`},
                monitorNum: {customize: `<div style='text-align:right'>${item.monitorNum && item.monitorNum != 0 ? item.monitorNum : '--'}</div>`},
                monitorPercent: {customize: `<div style='text-align:right'>${item.monitorPercent && item.monitorPercent != 0 ? item.monitorPercent : '--'}</div>`},
                onlineNum: {customize: `<div style='text-align:right'>${item.onlineNum && item.onlineNum != 0 ? item.onlineNum : '--'}</div>`},
                onlinePercent: {customize: `<div style='text-align:right'>${item.onlinePercent && item.onlinePercent != 0 ? item.onlinePercent : '--'}</div>`},
                todayAlarm: {customize: `<div style='text-align:right'>${item.todayAlarm && item.todayAlarm != 0 ? item.todayAlarm : '--'}</div>`},
                avgWorktime: {customize: `<div style='text-align:right'>${item.avgWorktime && item.avgWorktime != 0 ? item.avgWorktime : '--'}</div>`},
                handle: [{name: '查看详情', type: 'detail', data: item}]
              }
            })
          })
      // 按项目查询
      },
      // 获取无塔吊项目的列表
      getNoTowerDetailList () {
        let data = {
          'coId': this.currentUser.coId,
          'areaCode': this.areaId,
          'mid': this.currentUser.mid
          // 'page': this.noAccessPage,
          // 'pageSize': this.pageSize,
          // 'isExport': 0,  // 1导出
          // 'path': ''  // 下载路径
        }
        this.$axios({
            method: 'post',
            url: `${Vue.prototype.$site.videoServer}/api/towercrane/noMonitorList`,
            data: this.$qs.stringify(data, {indices: false}),
            paginate: true,
            paginId: 'page4'
          }).then(res => {
            if (res.data.data && res.data.data.dataList) {
              this.defaultNum = 1
              this.noAccessPage = res.data.data.pageNum
              this.detailDataList = res.data.data.dataList
              this.detailDataList = this.detailDataList.map(item => {
                return {
                  num: (this.noAccessPage - 1) * 10 + this.defaultNum++,
                  projectTitle: item.projectTitle,
                  departmentName: item.departmentName || '--',
                  memberName: item.memberName || '--',
                  onlineDay: {customize: `<span class='left'>${this.$moment(item.longGmtCreate).format('YYYY-MM-DD')}</span><span class='right'>已${item.onlineDay}天</span>`}
                }
              })
            } else {
              this.detailDataList = []
            }
          })
      },
      // 项目查找获取区域列表
      getDepartment () {
        getTowerDepartmentList({
          coId: this.currentUser.coId, //企业id
          mid: this.currentUser.mid
        }).then( res => {
          for (let item of res.data) {
            this.areaList[item.areaCode] = item.areaName
          }
        }).catch( err => {
          console.log(err)
        })
      },
      // 今日报警
      getTodayTower () {
        getComTodayTowerAlarm({
          coId: this.currentUser.coId,
          mid: this.currentUser.mid,
          areaCode: this.areaId // 区域id
        }).then(res => {
          this.totalWarnNum = res.data.alarmcount
          if (this.totalWarnNum === 0) {
            this.showNoNum = true
            return
          }
          this.totalWarnOptions.data = [
            {name: '超重', value: res.data.overweightcount,label: {show:true}, labelLine: {show: true} },
            {name: '防碰撞', value: res.data.knockcount,label: {show:true}, labelLine: {show: true} },
            {name: '限位', value: res.data.limitlocationcount,label: {show:true}, labelLine: {show: true} },
            {name: '限行区', value: res.data.limitareacount,label: {show:true}, labelLine: {show: true} },
            {name: '风速', value: res.data.windcount,label: {show:true}, labelLine: {show: true} },
            {name: '倾斜', value: res.data.anglecount,label: {show:true}, labelLine: {show: true} }
          ]
           for (let i = 0; i < this.totalWarnOptions.data.length; i++) {
            if (this.totalWarnOptions.data[i].value == 0) {
              this.totalWarnOptions.data[i].labelLine.show = false
              this.totalWarnOptions.data[i].label.show = false
            }
          }
          this.totalWarnOptions.allAlarm =  res.data.alarmcount || 0
           this.$nextTick(() => {
            this.totalWarnOption = pie(this.totalWarnOptions)
            this.totalWarn = this.$Echarts.init(this.$refs.towerMonitorEchart)
            this.totalWarn.setOption(this.totalWarnOption)
          })
        }).catch( err => {
          console.log(err)
        })
      },
      getInfoByAreaQuery () {
        return {
          coId: this.currentUser.coId,
          mid: this.currentUser.mid,
          keywords: this.searchAreaWord,
          groupObject: this.groupObject,
          order: this.order
        }
      },
      getInfoByProjectQuery () {
        return {
          coId: this.currentUser.coId,  // 企业id
          mid: this.currentUser.mid,  // 登录人id
          areaCode: this.areaId, // 区域编码
          keywords: this.searchKeyword,
          groupObject: this.groupObject,
          order: this.order
        }
      },
      getNoMonitorListQuery () {
        return {
          coId: this.currentUser.coId, // 企业id
          mid: this.currentUser.mid,// 登录人id
          areaCode: this.areaId // 区域编码
        }
      },
      exportExcel () {
        if (this.searchByPro) {
          this.$export(`${this.$site.videoServer}/api/towercrane/getComTowerByProjectExport`, this.getInfoByProjectQuery())
        } else {
          this.$export(`${this.$site.videoServer}/api/towercrane/getComTowerByAreaExport`, this.getInfoByAreaQuery())
        }
      },
      exportNoMonitorExcel () {
        this.$export(`${this.$site.videoServer}/api/towercrane/noMonitorListExport`, this.getNoMonitorListQuery())
      },
      close () {
        this.showDialog = false
        this.noTowerDialogShow = false
        this.todayDialogShow = false
      }
    }
}
</script>
<style lang="scss" scoped>
.environment-header{
    height: 60px;
    line-height: 30px;
    padding: 15px 20px 17px 20px;
    box-sizing: border-box;
    border-bottom: 1px $color-line solid;
    position: relative;
    .head-right {
      position: absolute;
      right: 20px;
      z-index: 6;
    }
  }
  .top-right {
    padding: 20px 20px 10px 20px;
    height: 30px;
    line-height: 30px;
    z-index: 6;
    span {
      line-height: 30px;
    }
  }
  .info {
    padding: 20px 20px 10px 20px;
    height: 30px;
    line-height: 30px;
    >div {
      font-size: 14px;
      color: #363c3c;
      display: inline-block;
      span {
        color: $color;
        font-weight: bold;
        display: inline-block;
        padding: 0 5px;
      }
    }
    >div:last-child {
      span {
        padding: 0 0 0 10px;
      }
    }
  }
  .exportExcel {
    div {
      line-height: 30px;
      display: inline-block;
      color: #939997;
    }
  }
</style>

